/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package network;

import java.io.*;
import java.net.DatagramPacket;
import java.net.MulticastSocket;
import java.net.DatagramSocket;
import javax.swing.JOptionPane;

import util.Message;
import view.MainFrames;

/**
 *
 * @author pol
 */
public class MessageReader implements Runnable {

    public MessageReader(UdpClient c) {
        client = c;
    }

    public void run() {
        DatagramSocket socket;
        try {
//            System.out.println(client.UDP_PORT);
            socket = new DatagramSocket(client.UDP_PORT);
        } catch (IOException e) {
            System.out.println("Message Reader didn't start.");
            e.printStackTrace();
            return;
        }

        while (true) {
            try {
                byte[] buffer = new byte[Message.MAX_MESSAGE_SIZE];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);
                Message msg = Message.getMessageFromBytes(buffer);
                if (!sameMessage.equals(msg)) {
                    if (sameMessageCount > 0) {
                        MainFrames.setSameMessageCount(sameMessageCount);
                        sameMessageCount = 0;
                    }
                    MainFrames.setMessage(msg);
                    sameMessage = msg;
                } else {
                    sameMessageCount++;
                }

            } catch (ClassNotFoundException e) {
                System.out.println("ClassNotFoundException in MessageReader.");
            } catch (IOException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, "ERROR! Request cannot be made at this time");
                System.out.println("IOException in MessageReader.");
            }
        }

    }
    private static Message sameMessage = new Message(null, null);
    private static int sameMessageCount = 0;
    private UdpClient client;
}
